<template>
	<view>
		<u-upload 
		class="upload"
		:custom-btn="true"
		:show-upload-list="false"
		:form-data="formData"
		:deletable="false"
		:multiple="false"
		:show-progress="false"
		max-count="1"
		:action="action"
		:beforeUpload="beforeUpload"
		@on-success="onSuccess"
		:max-size="5*1024*1024"
		ref="upload"
		
		>
			<view slot="addBtn">
				<u-avatar :src="this.vuex_user.avatar_url" size="140"></u-avatar>
			</view>
		</u-upload>
	</view>
</template>

<script>
	let _this={}
	export default {
		
		name:"oss-upload",
		data() {
			return {
				formData:{},
				action:"",
				loadName:""
			};
		},
		created() {
			_this = this
		},
		methods:{
			async beforeUpload(index, list) {
				//拿取上传的文件
				const {file} = list[0]
				
				// #ifdef H5
				const fileName = file.name
				// #endif
				
				// #ifndef H5
				const fileName = file.path
				// #endif
				//处理唯一文件名
				const sitty = fileName.slice(fileName.lastIndexOf("."))
				const loadName = _this.$u.guid(20) + sitty
				_this.loadName = loadName
				
				//请求oss
				const ossToken = await _this.$u.api.authGetOssToken()
				
				//获取上传文件后缀
				
				_this.action = ossToken.host
				
				
				_this.formData = {
					        'key' : loadName,
					        'policy': ossToken.policy,
					        'OSSAccessKeyId': ossToken.accessid,
					        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					        'signature': ossToken.signature
				} 
				
				return true
			},
			async onSuccess(){
				//删除预览图
				_this.$refs.upload.remove(0)
				//上传成功
				await _this.$u.api.updateAvatar({avatar:_this.loadName})

				_this.$u.toast("头像更新成功")
				//更新本地
				_this.$u.utils.updateUserInfo()

				
			}
		
		}
	}
</script>

<style lang="scss" scoped>
.upload{
	
	height: 70px;
	width: 70px;
}
</style>
